#include <windows.h>
#include <shlwapi.h>
#include <cstdio>
#include "libhttpd-helper.h"

HttpHelper::HttpHelper(char *host, int port){
	this->isRunning = false;
	this->serverOK = false;
	this->server = httpdCreate(host, port);
	if(this->server == NULL)
		this->serverOK = false;
	else this->serverOK = true;
	this->serverThread = CreateThread(NULL, NULL, ServerThreadProc, this, 0, NULL);
}

HttpHelper::~HttpHelper(){
	CloseHandle(this->serverThread);
	if(this->server){
		if (this->server->host)
			free(this->server->host);
		free(this->server);
	}
}

DWORD WINAPI ServerThreadProc( LPVOID lpParameter){
	HttpHelper *server = (HttpHelper *)lpParameter;
	server->isRunning = true;
	while(1 == 1) 
	{ 
		if (httpdGetConnection(server->server, NULL) < 0) 
			continue; 
		if(httpdReadRequest(server->server) < 0) 
		{ 
			httpdEndRequest(server->server); 
			continue; 
		} 
		httpdProcessRequest(server->server); 
		httpdEndRequest(server->server); 
	} 
}

void HttpHelper::AddDirectory(char *httppath, int (*preload)(void), char *dir){
	WIN32_FIND_DATA ffd;
	HANDLE hFind = INVALID_HANDLE_VALUE;
	char *filepath = NULL, *filepath2 = NULL, *filepath3 = NULL, *cwd;

	if(PathIsDirectory(dir)==false)
		return;
	httpdAddWildcardContent(this->server, httppath, preload, dir);
	filepath = new char[1024];
	if((dir[1] == ':') || ((dir[0] == '\\')&&(dir[1]=='\\')))
		sprintf(filepath, "%s\\*", dir);
	else{
		cwd = new char[1024];
		GetCurrentDirectory(1034, cwd);
		sprintf(filepath, "%s\\%s\\*",cwd, dir);
		delete cwd;
	}
	hFind = FindFirstFile(filepath, &ffd);
	if (INVALID_HANDLE_VALUE == hFind){ 
		return;
	}
	filepath2 = new char[1024];
	filepath3 = new char[1024];
	do
	{
		if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if((strcmp(ffd.cFileName, ".")==0) || (strcmp(ffd.cFileName, "..")==0))
				continue;
			sprintf(filepath2, "%s\\%s", dir, ffd.cFileName);
			sprintf(filepath3, "%s/%s", httppath, ffd.cFileName);

			AddDirectory(filepath3, preload, filepath2);
		}
	}
	while (FindNextFile(hFind, &ffd) != 0);
	
	delete filepath;
	delete filepath2;
	delete filepath3;
}